package company.permissionsystem.security.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import company.permissionsystem.security.util.AjaxResponse;
import company.permissionsystem.security.util.CustomException;
import company.permissionsystem.security.util.CustomExceptionType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  自定义Security失败处理配置
 * */
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     *  读取配置判断是否返回JSON数据
     * */
    @Value("${spring.security.loginType}")
    private String loginType;

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        if (loginType.equalsIgnoreCase("JSON")) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(AjaxResponse.error(
                    new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或密码错误！") )));
        } else {
            /**
             *  登陆失败跳转到登陆页面
             * */
            super.onAuthenticationFailure(request, response, exception);
        }


    }
}
